﻿using Microsoft.Xna.Framework;
using System;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;

namespace EAMF.Content.Projectiles
{
    public class EXTraceProj : ModProjectile
    {
        public ref float Timer => ref Projectile.ai[0];
        public override void SetDefaults()
        {
            Projectile.width = 1;
            Projectile.height = 1;
            Projectile.friendly = true;
            Projectile.timeLeft = 1000;
            Projectile.alpha = 255;
            base.SetDefaults();
        }
        public override void AI()
        {
            //Main.player[Projectile.owner].position代表发出这个弹幕的人
            Player player = Main.player[Projectile.owner];
            float t = (float)Timer / 10f;
            Dust dust = Dust.NewDustDirect(Projectile.Center, 1, 1, DustID.RedTorch, 0, 0, 100, Color.White, 2f);
            dust.noGravity = true;
            dust.velocity *= 0;
            dust.position = Projectile.Center + new Vector2((float)Math.Sin(2 * t) / 2, -(float)Math.Cos(3 * t) / 3) * 100f;

            if (Timer % 20 == 0)
            {
                float mindis = 1000f;
                Terraria.NPC target = null;
                //选取弹幕附近最近的一名敌人,地图所有npc都在Main.npc中
                foreach (var npc in Main.npc)
                {
                    //选取活着，敌对生物
                    if (npc.active && !npc.friendly)
                    {
                        float dis = Vector2.Distance(npc.Center, Projectile.Center);
                        if (dis < mindis)
                        {
                            mindis = dis;
                            target = npc;
                        }
                    }
                }
                if (target != null)
                {
                    Vector2 ProjToTarget = Vector2.Normalize(target.Center - Projectile.Center) * 25f;

                    IEntitySource source = Projectile.GetSource_FromAI();
                    Projectile.NewProjectile(source, Projectile.Center, ProjToTarget, ProjectileID.Starfury, Projectile.damage, Projectile.knockBack, Projectile.owner);
                }
            }
            Timer++;
        }
    }
}
